/*
 * @Author      : ZhouQiJun
 * @Date        : 2025-06-18 00:39:02
 * @LastEditors : ZhouQiJun
 * @LastEditTime: 2025-07-22 09:48:27
 * @Description :
 */
import { expect, test as setup } from '@playwright/test'
import fs from 'fs'
import { skip } from 'rxjs-compat/operator/skip'

import user from '../.auth/user.json'

const authFile = '.auth/user.json'

setup.skip('登录 by UI', async ({ page }) => {
  await page.goto('https://conduit.bondaracademy.com')
  const nav = page.getByRole('navigation')
  const goSignIn = nav.getByRole('list').getByRole('link', { name: 'sign in' }) // getByText('sign in')
  await goSignIn.click()
  await page.waitForURL(/login/, { waitUntil: 'domcontentloaded' })

  // FIXME  找不到 form 奇怪
  // page.getByRole('form')
  const signInForm = page.locator('form')
  const emailInput = signInForm.getByPlaceholder('Email')
  //const passwordInput = signInForm.getByPlaceholder('Password')
  const passwordInput = signInForm.getByRole('textbox', { name: 'Password' })
  const signInBtn = signInForm.getByRole('button', { name: 'Sign in' })

  await emailInput.fill('jackzhoumine@163.com')
  await passwordInput.fill('KKco8848!!')
  await signInBtn.click()

  // 登录成功
  const loginRes = await page.waitForResponse(/api\/users\/login/)
  expect(loginRes.status()).toEqual(200)
  // NOTE 保存 localStorage 到文件
  await page.context().storageState({ path: authFile })
})

setup('登录 by api', async ({ page, request }) => {
  // 有登录凭证
  if (process.env.ACCESS_TOKEN) return

  const loginInfo = { user: { email: 'jackzhoumine@163.com', password: 'KKco8848!!' } }
  const loginRes = await request.post('https://conduit-api.bondaracademy.com/api/users/login', {
    data: loginInfo,
  })

  expect(loginRes.status()).toEqual(200)

  const body = await loginRes.json()
  const accessToken = body.user.token
  if (!user.origins?.[0]?.localStorage?.[0]) {
    await page.context().storageState({ path: authFile })
  }
  if (user.origins?.[0]?.localStorage?.[0]) {
    user.origins[0].localStorage[0].value = accessToken
  } else {
    const localStorage = [{ value: accessToken, name: 'jwtToken' }]
    const origins = [{ localStorage, origin: 'https://conduit.bondaracademy.com' }]
    user.origins = origins
  }

  fs.writeFileSync(authFile, JSON.stringify(user))
  // NOTE 通过环境变量在不同的文件中共享变量
  process.env['ACCESS_TOKEN'] = accessToken
})
